<script setup>
import { onMounted, onUnmounted, ref, defineExpose,defineProps,watch, defineEmits } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { Location } from "@element-plus/icons-vue";

const props = defineProps({
    modelValue: String,
    placeName: String,
    canEdit: {
        type: Boolean,
        default: () => true
    }
});

const emit = defineEmits(["update:modelValue"]);
let map = null;

// 声明 placeSearch 变量
let placeSearch = null;
// 声明全局的AMaps变量
let AMaps = ref(null);
// 安全密钥
let securityJsCode = "21ac8e11acbf47484aa0f6f1aa3b20c7"
// 地图key
let mapKey = "dbaad984c2008b14522b212bf275e16e"

const searchPanelVisible = ref(false); // 控制search-panel的显示
const location = ref(Location);

onMounted(() => {
  initMap();
});

// 加载地图
const initMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode,
  };
  AMapLoader.load({
    key: mapKey,
    version: "2.0",
    plugins: ["AMap.PlaceSearch", "AMap.Geocoder", "AMap.InfoWindow"],
  })
    .then((AMap) => {
      AMaps.value = AMap;
      map = new AMap.Map("container", {
        viewMode: "3D",
        zoom: 11,
        center: [116.397428, 39.90923],
        dragEnable: props.canEdit, // 地图是否可通过鼠标拖拽平移，默认为true
        doubleClickZoom: props.canEdit, // 地图是否可通过双击鼠标放大地图，默认为true
        zoomEnable: props.canEdit, //地图是否可缩放，默认值为true
      });

      placeSearch = new AMap.PlaceSearch({
        // 搜索结果列表的容器
        autoFitView: true,
        extensions: "all",
      });

      props.canEdit && map.on("click", (e) => {
        // 点击坐标
        let markersPostion = [e.lnglat.lng, e.lnglat.lat];
        map.remove(map.getAllOverlays());

        // 获取地址
        let geoCoder = new AMap.Geocoder();
        geoCoder.getAddress(markersPostion, (status, result) => {
          if (status === "complete" && result.regeocode) {
            let location = e.lnglat;
            setMarker(location, result.regeocode);
          }
        });
      });
    })
    .catch((err) => {
      console.log("cuocuocucoc", err);
    });
};

// 设置地图的数据
const initMapData = (placeName) => {
    if (!AMaps.value) {
      return
    }
    let geoCoder = new AMaps.value.Geocoder();
    geoCoder.getLocation(placeName, function (status, result) {
    if (status === "complete" && result.info === "OK") {
        var location = result.geocodes[0].location;
        let geocodes = result.geocodes[0];
        setMarker(location, geocodes);
    } else {
        console.log("获取位置信息失败");
    }
    });
}

const poiList = ref([]);

// 点击查询事件
const searchMap = (newVal) => {
  if (newVal) {
    searchPanelVisible.value = true; // 显示search-panel
    placeSearch.search(newVal, (status, result) => {
      if (
        status === "complete" &&
        result.info === "OK" &&
        result.poiList &&
        result.poiList.pois
      ) {
        let list = result.poiList.pois;
        poiList.value = list;
      }
    });
  } else {
    searchPanelVisible.value = false; // 隐藏search-panel
  }
};

// 定义设置标注函数、添加信息窗体
const setMarker = (location, geocodes) => {
  // 获取到的坐标信息
  var lng = location.lng;
  var lat = location.lat;
  // 后续利用坐标进行标注
  if (lng && lat) {
    let marker = new AMaps.value.Marker({
      position: [lng, lat], // 标注的坐标位置
      title: geocodes.formattedAddress,
    });

    // 移除地图标注
    map.remove(map.getAllOverlays());

    marker.setMap(map);

    //信息窗体的内容
    var content = [`<div><b>${geocodes.formattedAddress}</b>`];

    //创建 infoWindow 实例
    var infoWindow = new AMaps.value.InfoWindow({
      content: content.join("<br>"), //传入字符串拼接的 DOM 元素
      anchor: "top-left",
    });

    //打开信息窗体
    infoWindow.open(map, location); //map 为当前地图的实例，map.getCenter() 用于获取地图中心点坐标。
    // 调整地图视野，确保所有标记都在视野中
    map.setFitView();
    // 设置完标注后，关闭搜索弹框
    searchPanelVisible.value = false;

    // 暴露地址内容给父组件
    emit("update:modelValue",geocodes.formattedAddress)
  }
};

// 点击查询单个的具体地址
const markerResult = (payload) => {
  let location = payload.location;
  let geocodes = {
    formattedAddress: payload.name,
  };
  setMarker(location, geocodes);
};

defineExpose({
  searchMap: searchMap,
  initMapData: initMapData
});

onUnmounted(() => {
  if (map) {
    map.destroy();
  }
});

watch([AMaps,()=> props.placeName],([newVal1,newVal2]) => {
  if (newVal1) {
    // 确保地图加载后再初始化地图数据
    initMapData(newVal2)
  }
})
</script>

<template>
  <div>
    <div id="container"></div>
    <!-- 搜索结果列表的容器 -->
    <ul
      id="search-panel"
      :style="{ display: searchPanelVisible ? 'block' : 'none' }"
      style="width: 300px; height: 400px; overflow-y: auto"
    >
      <li
        class="item-panel"
        v-for="(item, index) in poiList"
        :key="index"
        @click="markerResult(item)"
      >
        <div style="width: 20px">
          <location class="item-panel-location"></location>
        </div>
            <img class="item-panel-img"
          :src="item.photos && item.photos.length ? item.photos[0].url : ''"
          alt=""
        />
        <p style="flex:1;">{{ item.name }}</p>
      </li>
    </ul>
  </div>
</template>

<style scoped>
#container {
  width: 100%;
  height: 500px;
}
#search-panel {
  position: absolute;
  top: 35px;
  left: 10px;
  z-index: 999;
  background-color: white;
  border: 1px solid #ccc;
  padding: 10px;
}
.item-panel {
  display: flex;
  cursor: pointer;
  align-items: center;
}
.item-panel:hover {
  background: #dbdbdb;
}
.item-panel-location {
  width: 20px;
  height: 20px;
  color: red;
}
.item-panel-img {
  width: 40px;
  height: 40px;
  margin: 0 5px;
}
</style>
